import axios from 'axios';
import { useApartmentUserStoreHook } from '@/store/modules/apartmentUser';

// Create an axios instance with default config
const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000',
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // Needed for cookies/authentication
});

// Add interceptors for better error handling
api.interceptors.response.use(
  response => response,
  error => {
    console.error('API Error:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      data: error.response?.data,
      requestData: error.config?.data ? JSON.parse(error.config.data) : null
    });
    return Promise.reject(error);
  }
);

export interface Comment {
  id: string;
  content: string;
  authorId: string;
  postId: string;
  createdAt: Date;
  author: {
    id: string;
    username?: string; // 兼容旧版API
    name?: string;     // 数据库中的字段名
    nickname?: string;
    avatar?: string;   // 兼容旧版API
    avatarUrl?: string; // 数据库中的字段名
  };
  postTitle?: string;  // 帖子标题，用于显示在通知中
}

export interface CreateCommentDto {
  content: string;
  authorId: string;
  postId: string;
}

export interface CommentPaginationParams {
  page?: number;
  limit?: number;
}

/**
 * Get all comments for a specific post
 */
export const getCommentsByPost = async (
  postId: string, 
  params: CommentPaginationParams = { page: 1, limit: 50 }
): Promise<Comment[]> => {
  try {
    const response = await api.get(`/comments/post/${postId}`, { 
      params: { 
        ...params 
      } 
    });
    return response.data;
  } catch (error) {
    console.error(`Error fetching comments for post ${postId}:`, error);
    throw error;
  }
};

/**
 * Create a new comment
 */
export const createComment = async (commentData: CreateCommentDto): Promise<Comment> => {
  try {
    const response = await api.post('/comments', commentData);
    return response.data;
  } catch (error) {
    console.error('Error creating comment:', error);
    throw error;
  }
};

/**
 * Delete a comment
 */
export const deleteComment = async (id: string, userId: string): Promise<void> => {
  try {
    await api.delete(`/comments/${id}`, { data: { userId } });
  } catch (error) {
    console.error(`Error deleting comment ${id}:`, error);
    throw error;
  }
};

/**
 * Get recent comments from all posts
 * This is useful for notification displays
 */
export const getRecentComments = async (limit: number = 10): Promise<Comment[]> => {
  try {
    // 使用已有的getPosts获取最近的帖子
    const recentPosts = await axios.get(`${api.defaults.baseURL}/discussion-posts`, {
      params: {
        limit: 5, // 获取最近的5个帖子
        sort: 'createdAt:DESC' // 按创建时间排序
      },
      headers: api.defaults.headers,
      withCredentials: true
    });
    
    // 如果没有帖子，返回空数组
    if (!recentPosts.data || !Array.isArray(recentPosts.data) || recentPosts.data.length === 0) {
      return [];
    }
    
    // 获取这些帖子的所有评论
    const commentsPromises = recentPosts.data.map(post => 
      getCommentsByPost(post.id, { limit: 10 })
    );
    
    const postsComments = await Promise.all(commentsPromises);
    
    // 将所有评论合并为一个数组，按照时间排序，并限制数量
    const allComments = postsComments
      .flat()
      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
      .slice(0, limit);
    
    return allComments;
  } catch (error) {
    console.error('Error fetching recent comments:', error);
    return []; // 错误时返回空数组，而不是抛出错误
  }
};

/**
 * Get comments on posts authored by the current user
 * This is useful for personalized notifications
 */
export const getCommentsOnUserPosts = async (limit: number = 10): Promise<Comment[]> => {
  try {
    const apartmentUserStore = useApartmentUserStoreHook();
    const userId = apartmentUserStore.userId;
    
    if (!userId) {
      return [];
    }
    
    // 先获取用户发布的帖子
    const userPosts = await axios.get(`${api.defaults.baseURL}/discussion-posts/by-author/${userId}`, {
      headers: api.defaults.headers,
      withCredentials: true
    });
    
    // 如果用户没有发布过帖子，返回空数组
    if (!userPosts.data || !Array.isArray(userPosts.data) || userPosts.data.length === 0) {
      return [];
    }
    
    // 创建一个帖子ID到帖子标题的映射
    const postTitleMap = {};
    userPosts.data.forEach(post => {
      postTitleMap[post.id] = post.title;
    });
    
    // 获取这些帖子的所有评论
    const commentsPromises = userPosts.data.map(post => 
      getCommentsByPost(post.id, { limit: 5 })
    );
    
    const postsComments = await Promise.all(commentsPromises);
    
    // 将所有评论合并为一个数组，按照时间排序，并限制数量
    const allComments = postsComments
      .flat()
      .map(comment => {
        // 给每个评论添加帖子标题信息
        return {
          ...comment,
          postTitle: postTitleMap[comment.postId] || '未知帖子'
        };
      })
      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
      .slice(0, limit);
    
    return allComments;
  } catch (error) {
    console.error('Error fetching comments on user posts:', error);
    return []; // 错误时返回空数组，而不是抛出错误
  }
};

export default {
  getCommentsByPost,
  createComment,
  deleteComment,
  getRecentComments,
  getCommentsOnUserPosts
}; 